package com.java.util;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;

public class HashTable<K,V> extends Dictionary<K,V> implements Map<K,V>,Cloneable, Serializable {

    private static final int KEYS = 0;

    private static final int VALUES = 1;

    private static final int ENTRIES = 2;



    /**
     * hash table data
     * */
    private transient HashtableEntry<?,?>[] table;

    /**
     * the total number of entries in hash table
     * */
    private transient int count;


    private int threshold;


    private float loadFactor;


    private transient int modCount;

    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    public HashTable(int initCapacity,float loadFactor) {
        if(initCapacity<0)
            throw new IllegalArgumentException("Illegal Capacity: "+initCapacity);
        if(loadFactor<=0||Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal Load: "+loadFactor);
        if(initCapacity==0)
            initCapacity = 1;
        this.loadFactor = loadFactor;
        table = new HashtableEntry<?,?>[initCapacity];
        threshold = Math.min(initCapacity,MAX_ARRAY_SIZE+1);
    }

    public HashTable(int initCapacity){
        this(initCapacity,0.75f);
    }

    public HashTable(){
        this(11,0.75f);
    }

    public HashTable(Map<? extends K,?extends V> t){
        this(Math.max(2*t.size(),11),0.75f);
        putAll(t);
    }

    @Override
    public synchronized  int size() {
        return count;
    }

    @Override
    public synchronized boolean isEmpty() {
        return count==0;
    }

    public synchronized Enumeration<K> keys(){
        return this.getEnumeration(KEYS);
    }

    private <T>Enumeration<T> getEnumeration(int type){
        if(count==0){
            return Collections.emptyEnumeration();
        }else {
            return new Enumerator<>(type,false);
        }
    }

    private <T> Iterator<T> getIterator(int type){
        if(count == 0){
            return Collections.emptyIterator();
        }else{
            return new Enumerator<>(type,true);
        }
    }



    @Override
    public boolean containsKey(Object key) {
        return false;
    }

    @Override
    public boolean containsValue(Object valye) {
        return false;
    }

    @Override
    public synchronized Enumeration<V> elements() {
        return this.getEnumeration(VALUES);
    }

    @Override
    public  synchronized  V  get(Object key) {
        HashtableEntry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash&0x7fffffff)%tab.length;
        for(HashtableEntry<?,?> e = tab[index];e!=null;e = e.next){
            if((e.hash == hash)&&e.key.equals(key)){
                return (V) e.value;
            }
        }
        return null;
    }

    protected void rehash(){
        int oldCapacity = table.length;
        HashtableEntry<?,?>[] oldMap = table;
        int newCapacity = (oldCapacity<<1)+1;
        if(newCapacity-MAX_ARRAY_SIZE>0){
            if(oldCapacity == MAX_ARRAY_SIZE)
                return;
            newCapacity = MAX_ARRAY_SIZE;
        }

        HashtableEntry<?,?>[] newMap = new HashtableEntry[newCapacity];
        modCount++;
        threshold = (int) Math.min(newCapacity*loadFactor,MAX_ARRAY_SIZE+1);
        table = newMap;

        for(int i = oldCapacity;i-->0;){
            for(HashtableEntry<K,V> old = (HashtableEntry<K, V>) oldMap[i]; old!=null;){
                 HashtableEntry<K,V> e = old;
                 old = old.next;

                 int index = (e.hash&0x7FFFFFFF)%newCapacity;
                 e.next = (HashtableEntry<K, V>) newMap[index];
                 newMap[index] = e;
            }
        }
    }

    private void addEntry(int hash,K key,V value,int index){
        modCount++;
        HashtableEntry<?,?> tab[] = table;
        if(count>=threshold){
            rehash();
            tab = table;
            hash = key.hashCode();
            index = (hash&0x7FFFFFFF)%tab.length;
        }
        HashtableEntry<K,V> e = (HashtableEntry<K, V>) table[index];
        tab[index] = new HashtableEntry<>(hash,key,value,e);
        count++;
    }

    @Override
    public V put(K key, V value) {
        if(value==null)
            throw new NullPointerException();
        HashtableEntry<?,?>[] tab = table;
        int hash = key.hashCode();
        int index = (hash&0x7FFFFFFF)%tab.length;
        HashtableEntry<K,V> entry = (HashtableEntry<K, V>) tab[index];
        for(;entry!=null;entry = entry.next){
            if((entry.hash == hash)&&entry.key.equals(key)){
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }
        addEntry(hash,key,value,index);
        return null;
    }

    @Override
    public synchronized V remove(Object key) {
        HashtableEntry<?,?> tab[]  = table;
        int hash = key.hashCode();
        int index = (hash&0x7FFFFFFF)%tab.length;
        HashtableEntry<K,V> e = (HashtableEntry<K, V>) tab[index];
        for(HashtableEntry<K,V> prev = null;e!=null;prev = e,e = e.next){
            if((e.hash == hash)&&e.key.equals(key)){
                modCount++;
                if(prev!=null){
                    prev.next = e.next;
                }else{
                    tab[index] = e.next;
                }
                count -- ;
                V oldValue = e.value;
                e.value = null;
                return oldValue;
            }
        }
        return null;
    }

    @Override
    public synchronized void putAll(Map<? extends K, ? extends V> t) {
        for(Map.Entry<? extends K,? extends V> e:t.entrySet())
            put(e.getKey(),e.getValue());
    }

    @Override
    public void clear() {
       HashtableEntry<?,?>[] tab = table;
       modCount++;
       for(int index = tab.length;--index>0;){
           tab[index]=null;
       }
       count = 0;
    }

    public synchronized Object clone(){
        try{
            HashTable<?,?> t = (HashTable<?, ?>) super.clone();
            t.table = new HashtableEntry[table.length];
            for(int i = table.length;i-->0;){
                t.table[i] = (table[i]!=null)?
                        (HashtableEntry<?, ?>) table[i].clone() :null;
            }
            t.keySet = null;
            t.entrySet = null;
            t.values = null;
            t.modCount = 0;
            return t;

        }catch (CloneNotSupportedException e){
            throw new InternalError(e);
        }
    }

    public synchronized String toString(){
        int max = size()-1;
        if(max==-1)
            return "{}";
        StringBuilder sb = new StringBuilder();
        Iterator<Map.Entry<K,V>> it = entrySet.iterator();
        sb.append('{');
        for(int i = 0;;i++){
            Map.Entry<K,V> e = it.next();
            K key = e.getKey();
            V value = e.getValue();
            sb.append(key==this?"(this Map)":key.toString());
            sb.append("=");
            sb.append(value == this?"(this Map)":value.toString());
            if(i == max)
                return sb.append('}').toString();
            sb.append(", ");
        }

    }

    private transient volatile Set<K> keySet;
    private transient volatile Set<Map.Entry<K,V>> entrySet;
    private transient volatile  Collection<V> values;

    @Override
    public Set<K> keySet() {
        if(keySet==null){
            keySet = Collections.synchronizedSet(new KeySet());
        }
        return keySet;
    }

    public class KeySet extends AbstractSet<K>{

        @Override
        public Iterator<K> iterator() {
            return getIterator(KEYS);
        }

        @Override
        public int size() {
            return count;
        }

        public boolean contains(Object o){
            return containsKey(o);
        }

        public boolean remove(Object o){
            return HashTable.this.remove(o)!=null;
        }

        public void clear(){
            HashTable.this.clear();
        }


    }


    @Override
    public Collection<V> values() {
        if(values==null)
            values = Collections.synchronizedCollection(new ValueCollection());
        return values;
    }

    public synchronized int hashCode(){
        int h = 0;
        if(count == 0||loadFactor<0)
            return h;
        loadFactor = -loadFactor;
        HashtableEntry<?,?>[] tab = table;
        for(HashtableEntry<?,?> entry:tab){
            while(entry!=null){
                h+=entry.hashCode();
                entry = entry.next;
            }
        }
        loadFactor = -loadFactor;
        return h;
    }



    private class ValueCollection extends AbstractCollection<V>{

        @Override
        public Iterator<V> iterator() {
            return getIterator(VALUES);
        }

        @Override
        public int size() {
            return count;
        }

        public boolean contains(Object o){
            return containsValue(o);
        }

        public void clear(){
            HashTable.this.clear();
        }
    }

    public synchronized boolean equals(Object o){
        if(o == this)
            return true;
        if(!(o instanceof Map))
            return false;
        Map<?,?> t = (Map<?, ?>) o;
        if(t.size()!=size())
            return false;
        try{
            Iterator<Map.Entry<K,V>> i = entrySet().iterator();
            while(i.hasNext()){
                Map.Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if(value==null){
                    if(!(t.get(key)==null&&t.containsKey(key))){
                        return false;
                    }
                }else{
                    if(!value.equals(t.get(key))){
                        return false;
                    }
                }
            }
        }catch (ClassCastException e){
            return false;
        }catch (NullPointerException unused){
            return false;
        }
        return true;
    }

    @Override
    public Set<Entry<K, V>> entrySet() {
        if(entrySet==null){
            entrySet = Collections.synchronizedSet(new EntrySet());
        }
        return entrySet;
    }

    public class EntrySet extends AbstractSet<Map.Entry<K,V>>{

        @Override
        public Iterator<Entry<K, V>> iterator() {
            return getIterator(ENTRIES);
        }

        public boolean add(Map.Entry<K,V> o){
            return super.add(o);
        }


        public boolean contains(Object o){
            if( !(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> entry = (Entry<?, ?>) o;
            Object key = entry.getKey();
            HashtableEntry<?,?>[] tab = table;
            int hash = key.hashCode();
            int index = (hash&0x7FFFFFFF)%tab.length;
            for(HashtableEntry<?,?> e = tab[index];e!=null;e = e.next){
                if((e.hash==hash)&&e.equals(entry)){
                    return true;
                }
            }
            return false;
        }

        public boolean remove(Object o){
            if(!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> entry = (Entry<?, ?>) o;
            Object key = entry.getKey();
            HashtableEntry<?,?>[] tab  = table;
            int hash = key.hashCode();
            int index = (hash&0x7FFFFFFF)&tab.length;

            HashtableEntry<K,V> e = (HashtableEntry<K, V>) tab[index];
            for(HashtableEntry<K,V> prev = null;e!=null;prev = e,e = e.next){
                if(e.hash==hash&&e.equals(entry)){
                    modCount++;
                    if(prev!=null)
                        prev.next =e.next;
                    else
                        tab[index] = e.next;
                    count--;
                    e.value = null;
                    return true;
                }
            }
            return false;
        }

        @Override
        public int size() {
            return count;
        }

        public void clear(){
            HashTable.this.clear();
        }
    }

    private static class HashtableEntry<K,V> implements Map.Entry<K,V>{
        int hash;
        K key;
        V value;

        //新插入的值，用老值作为新值的next
        HashtableEntry<K,V> next;

        public HashtableEntry(int hash, K key, V value, HashtableEntry<K, V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        @Override
        protected Object clone(){
            return new HashtableEntry<>(hash,key,value,(next==null?null:(HashtableEntry<K,V>)next.clone()));
        }

        @Override
        public K getKey() {
            return key;
        }

        @Override
        public V getValue() {
            return value;
        }

        @Override
        public V setValue(V value) {
            if(value == null)
                throw new NullPointerException();
            V oldValue = this.value;
            this.value = value;
            return oldValue;
        }

        public boolean equals(Object o){
            if(!(o instanceof Map.Entry)){
                return false;
            }

            Map.Entry<?,?> e = (Map.Entry<?, ?>) o;

            return (key==null?e.getKey()==null:key.equals(e.getKey()))&&
                    (value==null?e.getValue()==null:value.equals(e.getValue()));
        }

        public int hashCode(){
            return hash^ Objects.hashCode(value);
        }

        public String toString(){
            return key.toString()+"="+value.toString();
        }
    }

    public synchronized V getOrDefault(Object key,V defaultValue){
        V result = get(key);
        return (null == result)?defaultValue:result;
    }

    public synchronized void forEach(BiConsumer<? super K,?super V> action){
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        HashtableEntry<?,?>[] tab = table;
        for(HashtableEntry<?,?> entry:tab){
            action.accept((K)entry.key,(V)entry.value);
            entry = entry.next;
            if(expectedModCount!=modCount){
                throw new ConcurrentModificationException();
            }
        }
    }


    @SuppressWarnings("unchecked")
    @Override
    public synchronized void replaceAll(BiFunction<? super K, ? super V, ? super V> function){
        Objects.requireNonNull(function);

        final int expectedModCount = modCount;
        HashtableEntry<K,V>[] tab = (HashtableEntry<K, V>[]) table;

        for(HashtableEntry<K,V> entry:tab){
            while(entry!=null){
                entry.value = (V) Objects.requireNonNull(function.apply(entry.key,entry.value));
                entry = entry.next;
                if(expectedModCount!=modCount){
                    throw new ConcurrentModificationException();
                }
            }
        }
    }

    @Override
    public synchronized V putIfAbsent(K key,V value){
         Objects.requireNonNull(value);
         HashtableEntry<?,?> tab[] = table;
         int hash = key.hashCode();
         int index = (hash&0x7FFFFFFF)&tab.length;
         HashtableEntry<K,V> entry = (HashtableEntry<K, V>) tab[index];
         for(;entry!=null;entry= entry.next){
             if((entry.hash==hash)&&entry.key.equals(key)){
                 V old = entry.value;
                 if(old == null){
                     entry.value = value;
                 }
                 return old;
             }
         }
         addEntry(hash,key,value,index);
         return null;

    }

    public synchronized boolean remove(Object key,Object value){
        Objects.requireNonNull(value);
        HashtableEntry<?,?>[] tab = table;
        int hash = key.hashCode();
        int index = (hash&0x7FFFFFFF)%tab.length;
        HashtableEntry<K,V> e = (HashtableEntry<K, V>) table[index];
        for(HashtableEntry<K,V> prev = null;e!=null;prev=e,e = e.next){
            if((e.hash==hash)&&e.key.equals(key)&&e.value.equals(value)){
                modCount++;
                if(prev!=null){
                    prev.next = e.next;
                }else{
                    tab[index] = e.next;
                }
                count--;
                e.value = null;
            }
        }
        return false;
    }

    @Override
    public synchronized boolean replace(K key,V oldValue,V newValue){
        Objects.requireNonNull(oldValue);
        Objects.requireNonNull(newValue);
        HashtableEntry<?,?>[] tab = table;
        int hash = key.hashCode();
        int index = (hash&0x7FFFFFFF)%tab.length;
        HashtableEntry<K,V> e = (HashtableEntry<K, V>) tab[index];
        for(;e!=null;e = e.next){
            if((e.hash==hash)&&e.key.equals(key)){
                if(e.value.equals(oldValue)){
                    e.value = newValue;
                    return true;
                }else{
                    return false;
                }
            }
        }
        return false;
    }

    @Override
    public synchronized V replace(K key,V value){
        Objects.requireNonNull(value);
        HashtableEntry<?,?>[] tab = table;
        int hash = key.hashCode();
        int index = (hash&0x7FFFFFFF)%tab.length;
        @SuppressWarnings("unchecked")
        HashtableEntry<K,V> e = (HashtableEntry<K, V>) tab[index];
        for(;e!=null;e = e.next){
            if((e.hash==hash)&&e.key.equals(key)){
                V oldValue = e.value;
                e.value = value;
                return oldValue;
            }
        }
        return null;
    }

    @Override
    public synchronized V computeIfAbsent(K key, Function<? super K,?extends V> mappingFunction){
        Objects.requireNonNull(mappingFunction);
        HashtableEntry<?,?>[] tab = table;
        int hash = key.hashCode();
        int index = (hash&0x7FFFFFFF)%tab.length;
        HashtableEntry<K,V> e = (HashtableEntry<K, V>) tab[index];
        for(;e!=null;e = e.next){
            if((e.hash==hash)&&e.key.equals(key)){
                return e.value;
            }
        }

        V newValue = mappingFunction.apply(key);
        if(newValue!=null){
            addEntry(hash,key,newValue,index);
        }
        return newValue;
    }

    public synchronized V computeIfPresent(K key,BiFunction<?super K,?super V,?extends V> remappingFunction){
        Objects.requireNonNull(remappingFunction);
        HashtableEntry<?,?>[] tab = table;
        int hash = key.hashCode();
        int index = (hash&0x7FFFFFFF)%table.length;
        HashtableEntry<K,V> e = (HashtableEntry<K, V>) tab[index];
        for(HashtableEntry<K,V> prev = null;e!=null;prev = e,e = e.next){
            if(e.hash==hash&&e.key.equals(key)){
                V newValue = remappingFunction.apply(key,e.value);
                if(newValue == null){
                    modCount++;
                    if(prev!=null){
                        prev.next = e.next;
                    }else{
                        tab[index] = e.next;
                    }
                    count--;
                }else{
                    e.value = newValue;
                }
                return newValue;
            }
        }
        return null;
    }

    @Override
    public synchronized V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        Objects.requireNonNull(remappingFunction);

        HashtableEntry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        HashtableEntry<K,V> e = (HashtableEntry<K,V>)tab[index];
        for (HashtableEntry<K,V> prev = null; e != null; prev = e, e = e.next) {
            if (e.hash == hash && Objects.equals(e.key, key)) {
                V newValue = remappingFunction.apply(key, e.value);
                if (newValue == null) {
                    modCount++;
                    if (prev != null) {
                        prev.next = e.next;
                    } else {
                        tab[index] = e.next;
                    }
                    count--;
                } else {
                    e.value = newValue;
                }
                return newValue;
            }
        }

        V newValue = remappingFunction.apply(key, null);
        if (newValue != null) {
            addEntry(hash, key, newValue, index);
        }

        return newValue;
    }

    @Override
    public synchronized V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
        Objects.requireNonNull(remappingFunction);

        HashtableEntry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        HashtableEntry<K,V> e = (HashtableEntry<K,V>)tab[index];
        for (HashtableEntry<K,V> prev = null; e != null; prev = e, e = e.next) {
            if (e.hash == hash && e.key.equals(key)) {
                V newValue = remappingFunction.apply(e.value, value);
                if (newValue == null) {
                    modCount++;
                    if (prev != null) {
                        prev.next = e.next;
                    } else {
                        tab[index] = e.next;
                    }
                    count--;
                } else {
                    e.value = newValue;
                }
                return newValue;
            }
        }

        if (value != null) {
            addEntry(hash, key, value, index);
        }

        return value;
    }

    private void writeObject(ObjectOutputStream s) throws IOException{
        HashtableEntry<Object,Object> entryStack = null;
        synchronized (this){
            s.defaultWriteObject();
            s.writeInt(table.length);
            s.writeInt(count);
            for(int index = 0;index<table.length;index++){
                HashtableEntry<?,?> entry = table[index];
                while(entry!=null){
                    entryStack = new HashtableEntry<>(0,entry.key,entry.value,entryStack);
                    entry = entry.next;
                }
            }
        }
        while(entryStack!=null){
            s.writeObject(entryStack.key);
            s.writeObject(entryStack.value);
            entryStack = entryStack.next;
        }
    }

    /**
     * Reconstitute the Hashtable from a stream (i.e., deserialize it).
     */
    private void readObject(java.io.ObjectInputStream s)
            throws IOException, ClassNotFoundException
    {
        // Read in the threshold and loadFactor
        s.defaultReadObject();

        // Validate loadFactor (ignore threshold - it will be re-computed)
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new StreamCorruptedException("Illegal Load: " + loadFactor);

        // Read the original length of the array and number of elements
        int origlength = s.readInt();
        int elements = s.readInt();

        // Validate # of elements
        if (elements < 0)
            throw new StreamCorruptedException("Illegal # of Elements: " + elements);

        // Clamp original length to be more than elements / loadFactor
        // (this is the invariant enforced with auto-growth)
        origlength = Math.max(origlength, (int)(elements / loadFactor) + 1);

        // Compute new length with a bit of room 5% + 3 to grow but
        // no larger than the clamped original length.  Make the length
        // odd if it's large enough, this helps distribute the entries.
        // Guard against the length ending up zero, that's not valid.
        int length = (int)((elements + elements / 20) / loadFactor) + 3;
        if (length > elements && (length & 1) == 0)
            length--;
        length = Math.min(length, origlength);
        table = new HashtableEntry<?,?>[length];
        threshold = (int)Math.min(length * loadFactor, MAX_ARRAY_SIZE + 1);
        count = 0;

        // Read the number of elements and then all the key/value objects
        for (; elements > 0; elements--) {
            @SuppressWarnings("unchecked")
            K key = (K)s.readObject();
            @SuppressWarnings("unchecked")
            V value = (V)s.readObject();
            // sync is eliminated for performance
            reconstitutionPut(table, key, value);
        }
    }

    /**
     * The put method used by readObject. This is provided because put
     * is overridable and should not be called in readObject since the
     * subclass will not yet be initialized.
     *
     * <p>This differs from the regular put method in several ways. No
     * checking for rehashing is necessary since the number of elements
     * initially in the table is known. The modCount is not incremented and
     * there's no synchronization because we are creating a new instance.
     * Also, no return value is needed.
     */
    private void reconstitutionPut(HashtableEntry<?,?>[] tab, K key, V value)
            throws StreamCorruptedException
    {
        if (value == null) {
            throw new java.io.StreamCorruptedException();
        }
        // Makes sure the key is not already in the hashtable.
        // This should not happen in deserialized version.
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        for (HashtableEntry<?,?> e = tab[index] ; e != null ; e = e.next) {
            if ((e.hash == hash) && e.key.equals(key)) {
                throw new java.io.StreamCorruptedException();
            }
        }
        // Creates the new entry.
        @SuppressWarnings("unchecked")
        HashtableEntry<K,V> e = (HashtableEntry<K,V>)tab[index];
        tab[index] = new HashtableEntry<>(hash, key, value, e);
        count++;
    }

    private class Enumerator<T> implements Enumeration<T>,Iterator<T>{

        HashtableEntry<?,?>[] table = HashTable.this.table;
        int index =table.length;

        HashtableEntry<?,?> entry;

        HashtableEntry<?,?> lastReturned;

        int type;

        boolean iterator;

        protected int expectedModCount = modCount;

        public Enumerator(int type, boolean iterator) {
            this.type = type;
            this.iterator = iterator;
        }

        @Override
        public boolean hasMoreElements() {
            HashtableEntry<?,?> e = entry;
            int i = index;
            HashtableEntry<?,?>[] t = table;

            while (e==null&&i>0){
                e = t[--i];
            }
            entry = e;
            index = i;
            return e!=null;
        }


        @Override
        public T nextElement() {
            HashtableEntry<?,?> et = entry;
            int i = index;
            HashtableEntry<?,?>[] t = table;
            while(et == null&&i>0){
                et = t[--i];
            }
            entry = et;
            index =i;
            if(et!=null){
                HashtableEntry<?,?> e = lastReturned = entry;
                entry = e.next;
                return type==KEYS? (T) e.key :(type == VALUES? (T) e.value : (T) e);
            }
            throw new NoSuchElementException("Hashtable Enumerator");
        }

        @Override
        public boolean hasNext() {
            return hasMoreElements();
        }

        @Override
        public T next() {
            if(modCount!=expectedModCount)
                throw new ConcurrentModificationException();
            return nextElement();
        }

        public void remove(){
            if(!iterator)
                throw new UnsupportedOperationException();
            if(lastReturned==null)
                throw new IllegalStateException("Hashtable Enumerator");
            if(modCount!=expectedModCount)
                throw new ConcurrentModificationException();

            synchronized (HashTable.this){
                HashtableEntry<?,?>[] tab = HashTable.this.table;
                int index = (lastReturned.hash&0x7FFFFFFF)%tab.length;
                HashtableEntry<K,V> e = (HashtableEntry<K, V>) tab[index];
                for(HashtableEntry<K,V> prev = null;e!=null;prev=e,e = e.next){
                    if(e == lastReturned){
                        modCount++;
                        expectedModCount++;
                        if(prev==null)
                            tab[index] = e.next;
                        else
                            prev.next = e.next;
                        count--;
                        lastReturned = null;
                        return;
                    }
                }
                throw new ConcurrentModificationException();
        }
        }
    }
}
